import 'package:concierge/app/widgets/ms_app_bar.dart';
import 'package:concierge/generated/locales.g.dart';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:url_launcher/url_launcher.dart';

class GeneralWebView extends StatefulWidget {
  const GeneralWebView({super.key});

  @override
  State<GeneralWebView> createState() => _GeneralWebViewState();
}

class _GeneralWebViewState extends State<GeneralWebView> {
  WebResourceError? error;
  String url = '';
  String title = '';
  double progress = 0;

  @override
  void initState() {
    super.initState();
    final args = Get.arguments;
    setState(() {
      url = args['url'] ?? '';
      title = args['title'] ?? '';
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: MSAppBar(title: title),
      body: Stack(
        children: [
          InAppWebView(
            initialSettings: InAppWebViewSettings(transparentBackground: true),
            initialUrlRequest: URLRequest(url: WebUri(url)),
            onPermissionRequest: (controller, request) async {
              return PermissionResponse(
                resources: request.resources,
                action: PermissionResponseAction.GRANT,
              );
            },
            shouldOverrideUrlLoading: (controller, navigationAction) async {
              final uri = navigationAction.request.url!;
              if (![
                "http",
                "https",
                "file",
                "chrome",
                "data",
                "javascript",
                "about",
              ].contains(uri.scheme)) {
                await launchUrl(uri);
                return NavigationActionPolicy.CANCEL;
              }
              return NavigationActionPolicy.ALLOW;
            },
            onReceivedError: (controller, request, err) {
              setState(() {
                error = err;
              });
            },
            onProgressChanged: (controller, progress) {
              setState(() {
                this.progress = progress / 100;
              });
            },
          ),
          if (error != null)
            Padding(
              padding: EdgeInsets.symmetric(horizontal: 24.w),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                spacing: 10.w,
                children: [
                  Text(
                    LocaleKeys.webview_error_title.tr,
                    style: context.textTheme.titleMedium,
                    textAlign: TextAlign.center,
                  ),
                  RichText(
                    text: TextSpan(
                      text: url,
                      style: context.textTheme.bodyMedium?.copyWith(
                        color: context.theme.colorScheme.primaryFixed,
                      ),
                      children: [
                        TextSpan(
                          text: LocaleKeys.webview_error_description.trParams({
                            'url': '',
                          }),
                          style: context.textTheme.bodyMedium,
                        ),
                      ],
                    ),
                    textAlign: TextAlign.center,
                  ),
                  SizedBox(
                    height:
                        MSAppBar().preferredSize.height +
                        kToolbarHeight +
                        context.mediaQueryPadding.bottom,
                  ),
                ],
              ),
            ),
          if (error == null && progress < 1.0)
            LinearProgressIndicator(
              value: progress,
              color: context.theme.colorScheme.primaryFixed,
              backgroundColor: Colors.transparent,
            ),
        ],
      ),
    );
  }
}
